/**
 * FileName: EchoServer
 * Author:   powersi
 * Date:     2021/3/1 17:48
 * Description:
 */
package com.demo.zm.netty.sample.echo;

import com.demo.zm.netty.sample.echo.codec.ClientLengthDecoder;
import com.demo.zm.netty.sample.echo.codec.ClientLengthEncoder;
import com.demo.zm.netty.sample.echo.codec.ServerStringDecoder;
import com.demo.zm.netty.sample.echo.codec.ServerStringEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Description: 
 * Author:      powersi
 * Date:        2021/3/1 17:48
 */
public class ChatClient {


    public static void main(String[] args) throws InterruptedException {


        Bootstrap serverBootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup(new DefaultThreadFactory("client"));

        serverBootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline =  socketChannel.pipeline();
                        pipeline.addLast(new ClientLengthEncoder());
                        pipeline.addLast(new ClientLengthDecoder());
                        pipeline.addLast(new ServerStringEncoder());
                        pipeline.addLast(new ServerStringDecoder());
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
//                        pipeline.addLast(new EchoClientHandler());
                    }
                });

        try {
            Channel channel = serverBootstrap.connect("127.0.0.1", 8099).sync().channel();
            ChannelFuture channelFuture = null;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = bufferedReader.readLine();
                if (line == null){
                    break;
                }

                channelFuture = channel.writeAndFlush(line + "\r\n");
                if ("bye".equalsIgnoreCase(line)){
                    channel.closeFuture().sync();
                    break;
                }
            }
            if (channelFuture != null){
                channelFuture.sync();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
